package my.sample.ha.cluster;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.View;

public class SimpleChat extends ReceiverAdapter {

    JChannel channel;
    String userName=System.getProperty("user.name", "n/a");

    private void start() throws Exception {
        channel=new JChannel();
        channel.setReceiver(this);
        channel.connect("ChatCluster");
        eventLoop();
        channel.close();
    }
	
	public static void main(String[] args) throws Exception {
		new SimpleChat().start();
	}
	
	private void eventLoop() {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		while ( true ) {
			try {
				System.out.println("> "); System.out.flush();
				String line = in.readLine().toLowerCase();
				
				if ( line.startsWith("quit") || line.startsWith("exit"))
					break;
				line = "[" + userName + "] : " + line;
				
				// public Message(Address dest, Address src, Object obj)
				Message message = new Message(null, null, line);
				channel.send(message);
				
			} catch(Exception e) {
				
			}
		}
	}
	
	public void viewAccepted(View newView) {

	    System.out.println("** view: " + newView);

	}


	public void receive(Message msg) {

	    System.out.println(msg.getSrc() + ": " + msg.getObject());

	}
	
	
}
